﻿
using SmartAnswerPlatform.Common;
using SmartAnswerPlatform.IRepository;
using SmartAnswerPlatform.IService;
using SmartAnswerPlatform.Models.Entitys.Base;
using SqlSugar;
using System.Collections.Generic;
using System.Linq.Expressions;

namespace SmartAnswerPlatform.Service
{
    public class BaseService<TEntity, TViewModel> : IBaseService<TEntity, TViewModel>
        where TEntity : BaseEntity, new()
        where TViewModel : class, new()
    {
        protected readonly IBaseRepository<TEntity> _repository;


        public BaseService(IBaseRepository<TEntity> repository)
        {
            _repository = repository;
        }

        public async Task<TViewModel> FindById(string id)
        {
            TEntity entity = await _repository.FindById(id);
            return MapperHelper.Copy<TEntity, TViewModel>(entity);
        }

        public async Task<List<TViewModel>> FindByIds(List<string> ids)
        {
            List<TEntity> list = await _repository.FindByIds(ids);
            return MapperHelper.CopyList<TEntity, TViewModel>(list);
        }

        public async Task<List<TViewModel>> FindAll()
        {
            List<TEntity> list = await _repository.FindAll();
            return MapperHelper.CopyList<TEntity, TViewModel>(list);
        }

        public async Task<int> Update(TViewModel viewModel)
        {
            TEntity entity = MapperHelper.Copy<TViewModel, TEntity>(viewModel);
            return await _repository.Update(entity);
        }

        public async Task<int> UpdateRange(List<TViewModel> viewModels)
        {
            List<TEntity> entities = MapperHelper.CopyList<TViewModel, TEntity>(viewModels);
            return await _repository.UpdateRange(entities); ;
        }

        public async Task<int> Delete(string id)
        {
            return await _repository.Delete(id);
        }

        public async Task<int> DeleteRange(List<string> ids)
        {
            return await _repository.DeleteRange(ids);
        }

        public async Task<TViewModel> Insert(TViewModel viewModel)
        {
            TEntity entity = MapperHelper.Copy<TViewModel, TEntity>(viewModel);
            return MapperHelper.Copy<TEntity, TViewModel>(await _repository.Insert(entity));
        }

        public async Task<int> InsertRange(List<TViewModel> viewModels)
        {
            List<TEntity> entitys = MapperHelper.CopyList<TViewModel, TEntity>(viewModels);
            return await _repository.InsertRange(entitys);
        }
    }
}
